// window.parent.location.hash = '#c=60071010';

import React, { Component } from 'react';

import './index.less';

import mockFn from '../mock';
import {  toast } from 'nc-lightapp-front';

// 功能函数
import processTemplate from './functions/processTemplateData';
import getMainTableData from './functions/getMainTableData';
import handleTableSelect from './functions/handleTableSelect';
import selectTree from './functions/selectTree';
import toggleModal from './functions/toggleModalVisible';
import getSelectedField from './functions/getSelectedField';
import processEditPageTemplate from './functions/processEditPageTemplate';
import deleteSubTableRows from './functions/deleteSubTableRows';
import addSubTableRow from './functions/addSubTableRow';
import pasteSubTableRow from './functions/pasteSubTableRow';
import insertSubTableRow from './functions/insertSubTableRow';
import deleteMainTableRow from './functions/deleteMainTableRow';
import batchAddSub from './functions/batchAddSub';
import cancelEdit from './functions/cancelEdit';
import selectAll from './functions/selectAll';
import printPage from './functions/print';
import fileManager from './functions/fileManager';
import printOutput from './functions/printOutput';
import toEditPage from './functions/toEditPage';
import getModifyData from './functions/getModifyData';
import entryApply from './functions/entryApply';
import relativeQueryCard from './functions/relativeQueryCard';
import ctrtCodesRollBack from './functions/ctrtCodesRollBack';
import setButtonStatus2 from './functions/setButtonStatus2';

import language from '../language';

import Layout from './Layout';
import copyRow from './functions/copyRow';
import checkDbClick from './functions/checkDbClick';

import pageIns from '../pageIns';

import { snCreateUIDom, handleHash, getAppPageConfig } from '../../../../hrpub/common/utils/utils';


class EntryMng extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.table('sort');
            props.use.editTable('ncc600704list', 'batchAddSubTaleTemplate');
            props.use.form('only_info_template', 'batch_edit', 'batchAddSub', 'entryinfo');
            props.use.form('bd_psndoc', 'hi_psnorg_h', 'hi_psnjob_h');
            props.use.cardTable(...props.cardTableList);
            if (props.templateData.template && props.templateData.template.formrelation) {
                Object.entries(props.templateData.template.formrelation).forEach(val => {
                    val[1].forEach(item => {
                        props.use.form(item)
                    })
                })
            }
            if (props.templateData.template.formassociatedrelation) {
                let fsrelation = props.templateData.template.formassociatedrelation
                Object.keys(fsrelation).forEach(key => {
                    if (fsrelation[key].formtabs) {
                        fsrelation[key].formtabs.forEach(item => {
                            props.use.form(item)
                        })
                    }
                })
            }
        }
        this.config = getAppPageConfig();

        this.state = {
            pks: [],
            humanResourceOrganizationValue: {}, // 人力资源选择的值，大概率只用refpk属性
            page: 'main', // main  add-new 当前是哪个页面
            searchModalVisible: false, // 查询弹窗的显示隐藏
            onlyInfoModalVisible: false, // 唯一性信息验证弹窗的显示隐藏
            showZRCKModal: false,//转入人才库
            zywhdyModalVisible: false, //职业病危害调研弹窗
            departmentTreeData: [], // 左侧部门树的数据
            currentSelectDepartment: '', // 当前选中的部门
            searchModalValue: {}, // 存储查询弹窗的输入值
            queryOid: '',
            include_child_depts: true, // 包含下级部门人员
            include_child_orgs: false, // 包含下级组织人员
            sortModalVisible: false,
            pageInfo: {
                pageSize: 10,
                pageIndex: 0,
                total: 0,
                totalPage: 1
            },
            hasSearched: false, // true表示已经进行过一次正常查询
            selectedRows: [], // 选中的行
            pk_psnjob: '',
            showTableCheckbox: true,
            switchToDocModalVisible: false,
            uniqueFields: '',
            addPageTemplate: {}, // 新增页面的模版填充数据数据, 从onlyinfomodal模块提交后返回更新
            batchEditModalVisible: false, // 批改弹窗显示/隐藏标志
            pageFrom: '', // 点击了哪个按钮转换的页面 add / modify
            batchAddSubVisible: false, // 批量添加子集弹窗的显示/隐藏标示
            copyData: {}, // 新增页面的表格，复制下来的数据, key值是表格的tableid
            show_all_info: false, // 显示所有信息
            show_on_job_psn: true, // 显示在职人员
            rosterModalVisible: false, // 联查花名册弹窗
            mainTableData: {}, // 主表的数据
            imageData: '', // 头像的base64码
            subTableEditable: true, // 为true代表子表可以编辑
            showUploader: false, // 附件管理显示隐藏,
            printData: {
                filename: language['hi6007-000099'], /* 国际化处理： 员工信息*/
                funcode: '60071010',      //功能节点编码，即模板编码
                nodekey: '60071010list',
                oids: '',   // 单据pk  oids含有多个元素时为批量打印,
                outputType: 'output'
            }, // 输出的配置数据

            buttonStatus: 'main', // 按钮的状态
            fixTemplate: {}, // 第一次的模版数据
            disableUpload: false, // 禁止上传照片
            mainPageButtonClick: '', // 用来存储到底是点击了新增还是点击了修改,之有点击新增，修改，或者双击才能改变这个值
            clickRow: null, // 被点击高亮的行数据
            modifyData: null, // 获取到的编辑页面的初始化数据
            zywhdyData: {}, // 获取到职业危害调研的数据
            mainTableHeight: 350, // 主表格的高度
            entryApplyModalVisible: false, // 生成入职申请弹窗显示隐藏
            entryApplyListPks: '', // 生成入职申请弹窗的提交参数 listpks
            assignVisible: false, // 生成入职申请直接提交时是否可指派
            compositedata: null, // 指派数据
            billids: [], // 生成入职申请提交的单据号
            pageHeight: 0, // 页面app高度
            buttons: [], // 保存现有按钮
            photoRequired: false, // 照片是否需要必填,
            photoConf: {}, //照片的配置
            show_reject_offer: false, // 是否展示拒绝offer人员
            show_refuse_entry: false, // 显示拒绝入职人员
            include_entry_apply: false, // 显示已提交入职申请人员
            importModalVisible: false, // 导入
            contartNewCodeList: [] // 合同子集编码规则
        };

        this.updateState = this.updateState.bind(this);
        this.handleTableSelect = this.handleTableSelect.bind(this);
        this.getMainTableData = this.getMainTableData.bind(this);
        this.goBackToMainPage = this.goBackToMainPage.bind(this);
        this.getRef = this.getRef.bind(this);
        this.selectTree = this.selectTree.bind(this);
        this.toggleModal = this.toggleModal.bind(this);
        this.sortModalOnSure = this.sortModalOnSure.bind(this);
        this.copyRow = this.copyRow.bind(this);
        this.deleteRow = this.deleteRow.bind(this);
        this.pasteRow = this.pasteRow.bind(this);
        this.addRow = this.addRow.bind(this);
        this.toEditPage = this.toEditPage.bind(this);
        this.getModifyData = this.getModifyData.bind(this);
        this.processEditPageTemplate = this.processEditPageTemplate.bind(this);
        this.insertRow = this.insertRow.bind(this);
        this.deleteMainTableRow = this.deleteMainTableRow.bind(this);
        this.batchAddSub = this.batchAddSub.bind(this);
        this.getMultiLanguage = this.getMultiLanguage.bind(this);
        this.cancelEdit = this.cancelEdit.bind(this);
        this.selectAll = this.selectAll.bind(this);
        this.print = this.print.bind(this);
        this.fileManager = this.fileManager.bind(this);
        this.printOutput = this.printOutput.bind(this);
        this.setButtonStatus2 = this.setButtonStatus2.bind(this);
        this.getSelectedField = this.getSelectedField.bind(this);
        this.checkDbClick = this.checkDbClick.bind(this);
        this.setUpLoaderRef = this.setUpLoaderRef.bind(this);
        this.entryApply = this.entryApply.bind(this);
        this.getPageHeight = this.getPageHeight.bind(this);
        this.relativeQueryCard = this.relativeQueryCard.bind(this);
        this.getRefInstants = this.getRefInstants.bind(this);
        this.getWpsRefInstants = this.getWpsRefInstants.bind(this)
        this.ctrtCodesRollBack = this.ctrtCodesRollBack.bind(this);
        this.zRCKModalOnSure = this.zRCKModalOnSure.bind(this);


    }

    // 生成入职申请
    entryApply() {
        entryApply.call(this);
    }

    // 设置上传照片的那个那个ref
    setUpLoaderRef(upload) {
        this.upload = upload;
        this.upload.setState({
            disableUpload: this.state.disableUpload
        });
    }

    // 双击的时候检测是否可以预览
    checkDbClick(callback, pk_psnjob) {
        return checkDbClick.call(this, callback, pk_psnjob);
    }

    // 统一设置按钮状态
    setButtonStatus2(buttonStatus) {
        setButtonStatus2.call(this, buttonStatus);
    }

    // 输出
    printOutput() {
        printOutput.call(this);
    }

    // 附件管理
    fileManager() {
        fileManager.call(this);
    }

    // 打印
    print() {
        printPage.call(this);
    }

    // 处理新增/修改页面初始化返回的模版数据
    processEditPageTemplate(cb) {
        processEditPageTemplate.call(this, cb);
    }

    // 获取修改页面数据
    async getModifyData(cb, pk_psnjob, refresh) {
        await getModifyData.call(this, cb, pk_psnjob, refresh);
    }

    // 跳转到新增/修改页面
    toEditPage(pageFrom, cb, pk_psnjob) {
        toEditPage.call(this, pageFrom, cb, pk_psnjob);
    }

    // 选择左树
    selectTree(pk) {
        selectTree.call(this, pk)
    }

    // 主表选择
    handleTableSelect(props, moduleId, record, index) {
        handleTableSelect.call(this, props, moduleId, record, index);
    }

    // 通用更新state
    updateState(data, callback = () => {
    }) {
        this.setState(data, callback);
    }

    // 获取多语言
    getMultiLanguage() {
        return new Promise((resolve, reject) => {
            this.props.MultiInit.getMultiLang({
                moduleId: 'hi6007',
                domainName: 'hrhi',
                callback: (json, status, init) => {
                    Object.assign(language, json);
                    resolve();
                }
            });
        });
    }

    componentDidMount() {
        let { meta, button, templateData } = this.props;


        // 获取多语言数据
        this.getMultiLanguage()
            .then(() => {
                // snCreateUIDom(this.config, reqData, (data) => {
                let data = templateData;
                let photoConf = data['template']['bd_psndoc'].items.filter(item => item.attrcode === 'photo')[0];
                let photoRequired = photoConf.required;

                data.template['entryinfo'] = data['batch_add']['entryinfo'];

                this.setState({
                    context: data.context,
                    queryOid: data.template.ncc600704query.oid,
                    fixTemplate: data.template,
                    buttons: data.button,
                    photoRequired: photoRequired,
                    photoConf: photoConf
                });

                Object.assign(data.template, mockFn().template);

                meta.setMeta(processTemplate.call(this, data.template) || {});
                button.setButtons(data.button || {});
                this.setButtonStatus2('init');
                // 暂时还没有联查卡片功能
                button.setButtonDisabled({
                    cardrpt: true,
                    entryapply: true
                });
                this.getPageHeight();
                let keySessionS = 'appTempletStorage_' + this.config.appcode + '_' + this.config.pagecode;
                pageIns.ins.myState.keySessionS = keySessionS;
                console.log(data);
                // });
            });

    }

    // 获取页面高度
    getPageHeight() {
        if (window.getComputedStyle) {
            let height = window.getComputedStyle(document.getElementById('app')).height.replace('px', '');

            this.setState({
                pageHeight: height
            });
        }
    }

    // 获取主表数据
    getMainTableData() {
        getMainTableData.call(this);
    }

    // 返回主表
    goBackToMainPage() {
        this.setState({
            page: 'main',
            selectedRows: this.props.editTable.getCheckedRows('ncc600704list'),
            modifyData: null,
            addPageTemplate: null
        });
        // 每次返回主表的时候，都会重新请求主表的数据
        this.getMainTableData();
        this.setButtonStatus2('mainHadData');

        this.props.meta.setMeta(this.state.fixTemplate);
    }

    // 获取组件的实例对象
    getRef(refName) {
        return this[refName];
    }

    // 切换各种弹窗显示隐藏，type为弹窗的显示隐藏state的key值
    toggleModal(type, visible) {
        return toggleModal.call(this, type, visible);
    }

    // 排序弹窗点击确定的回调
    sortModalOnSure() {
        if (this.state.hasSearched) {
            this.getMainTableData();
        }
    }
    // 转人才库点击确定的回调
    zRCKModalOnSure() {
        this.updateState({
            showZRCKModal: false
        });
        if (this.state.hasSearched) {
            this.getMainTableData();

        }
        toast({ color: 'success', content: '转入人才库成功' });
    }
    // 根据选中的行，拿出需要的字段
    getSelectedField(field, all) {
        return getSelectedField.call(this, field, all);
    }

    // 新增页面的表格复制
    copyRow(tableId, data) {
        copyRow.call(this, tableId, data);
    }

    // 新增页面删除表格行
    deleteRow(tableId, indexList) {
        return deleteSubTableRows.call(this, tableId, indexList);
    }

    // 新增页面粘贴
    pasteRow(tableId, index) {
        return pasteSubTableRow.call(this, tableId, index);
    }

    // 新增页面新增加一行
    addRow(tableId, index, values = {}, focus = false) {
        return addSubTableRow.call(this, tableId, index, values = {}, focus = false);
    }

    // 新增页面插入一行
    insertRow(tableId, index) {
        return insertSubTableRow.call(this, tableId, index);
    }

    // 主表删除方法
    deleteMainTableRow() {
        return deleteMainTableRow.call(this);
    }

    // 触发批量添加子集功能
    batchAddSub() {
        return batchAddSub.call(this);
    }

    // 取消编辑，进入预览态
    cancelEdit() {
        cancelEdit.call(this);
    }

    // 点击全选按钮
    selectAll(props, tableId, status, length) {
        selectAll.call(this, status);
    }

    relativeQueryCard() {
        relativeQueryCard.call(this);
    }

    // 获取联查卡片的实例对象
    getRefInstants(ref) {
        this.cardView = ref;
    }

    // 获取联查卡片的实例对象
    getWpsRefInstants(ref) {
        this.wpsview = ref;
    }

    //拿到合同子集新增的编码
    ctrtCodesRollBack(tableData) {
        return ctrtCodesRollBack.call(this, tableData)
    }

    render() {




        return (
            <Layout
                {...this.props}
                {...this.state}
                ref={ref => {
                    if (ref) {
                        this.headerRef = ref.headerRef;
                        this.batchEdit = ref.batchEdit;
                        this.printOutputRef = ref.printOutputRef;
                    }
                }}
                updateState={this.updateState}
                getMainTableData={this.getMainTableData}
                getRef={this.getRef}
                toEditPage={this.toEditPage}
                deleteMainTableRow={this.deleteMainTableRow}
                batchAddSub={this.batchAddSub}
                goBackToMainPage={this.goBackToMainPage}
                print={this.print}
                fileManager={this.fileManager}
                printOutput={this.printOutput}
                setButtonStatus2={this.setButtonStatus2}
                selectTree={this.selectTree}
                handleTableSelect={this.handleTableSelect}
                selectAll={this.selectAll}
                copyRow={this.copyRow}
                deleteRow={this.deleteRow}
                addRow={this.addRow}
                cancelEdit={this.cancelEdit}
                getModifyData={this.getModifyData}
                pasteRow={this.pasteRow}
                processEditPageTemplate={this.processEditPageTemplate}
                sortModalOnSure={this.sortModalOnSure}
                zRCKModalOnSure={this.zRCKModalOnSure}
                toggleModal={this.toggleModal}
                getSelectedField={this.getSelectedField}
                setUpLoaderRef={this.setUpLoaderRef}
                entryApply={this.entryApply}
                relativeQueryCard={this.relativeQueryCard}
                language={language}
                getRefInstants={this.getRefInstants}
                getWpsRefInstants={this.getWpsRefInstants}
                ctrtCodesRollBack={this.ctrtCodesRollBack}

            />
        );
    }
}

export default handleHash('2019', 'c=60071010&p=60071010p')(EntryMng);
